package com.xxgc.springboot.realm;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xxgc.springboot.entity.Users;
import com.xxgc.springboot.service.IUsersService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import java.util.HashSet;
import java.util.Set;

/**
 * @program: springboot
 * @description: 用户Realm
 * @author: Mr.abel(ShiJiaYi)
 * @create: 2022-09-29 09:44
 * 一种状态，或者一种登录方式，一个Realm
 * 用于给对象授权
 **/
@Slf4j
public class UserRealm extends AuthorizingRealm {
    @Autowired
    private IUsersService ius;

    @Value("${system.md5-key}")
    private String md5Key;

    //去获取到授权的信息
    //权限
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //实例化授权对象
        SimpleAuthorizationInfo sai = new SimpleAuthorizationInfo();
        //通过Session获取id
        Long id = (Long) SecurityUtils.getSubject().getSession().getAttribute("id");
        int uid = id.intValue();
        //获取对应的权限
        Set<String> perms = new HashSet<>(ius.selectPerByUserId(uid));
        //给授权对象添加配置
        sai.setStringPermissions(perms);

        //角色集合
        Set<String> roles = new HashSet<>();
        roles.add(ius.selectRoleByUserId(uid));
        sai.setRoles(roles);

        return sai;
    }

    //从数据库获取当前用户的账号、密码信息（认证）
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //1、获取用户名
        String uname = (String) token.getPrincipal();
        //2、通过数据库查询出对应的用户
        QueryWrapper<Users> oqw = new QueryWrapper<>();
        oqw.eq("uname",uname);
        Users users = ius.getOne(oqw);
        //查询不到用户
        if(users == null){
            //没有找到认证信息的异常
            throw new UnknownAccountException();
        }
        //对数据进行验证
        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(
                users.getUname(),
                users.getUpass(),
                //盐值
                ByteSource.Util.bytes(md5Key+users.getSalt()),
                getName()
        );
        //拿到用户id
        Long id = users.getId();
        //通过Shiro自己的Session来保存用户信息
        SecurityUtils.getSubject().getSession().setAttribute("id",id);

        return simpleAuthenticationInfo;
    }

}
